package gui.clock;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JPanel;
import common.EarthSimSettings;

/**
 * This JPanel subclass uses the DateFormat class
 * to display the current time.
 */
public class DateTimePanel extends JPanel {
  private static final long serialVersionUID = 8911893845292571204L;
  private EarthSimSettings settings = EarthSimSettings.getInstance();
  private DateFormat dateFormat;
  private boolean firstPass = true;
  private int fMsgX, fMsgY;
  private Font font = new Font("SansSerif", Font.BOLD, 14);
  private long currentDateTime;
  private Calendar cal;
  private Dimension dim = new Dimension(320,30);
  
  /** Get the DateFormat object with the default time style. **/
  public DateTimePanel() {
    dateFormat = new SimpleDateFormat("EEE, MMM d, yyyy HH:mm z Z");
    dateFormat.setTimeZone(settings.getTimeZone());
    
    cal = settings.getCalendar();
    init();
    
    setPreferredSize(dim);
    setMaximumSize(dim);
  }
  
  private void init() {
    cal.set(2000, 2, 21, 0, 0, 0);    
    currentDateTime = cal.getTimeInMillis();
  }
  
  public long getTime() {
    return currentDateTime;
  }
    
  public void setDateTime(long dateTime) {
    cal.setTime(new Date(dateTime));
    currentDateTime = cal.getTimeInMillis();
    this.repaint();
  }
  
  public void increment(long milliSecs) {
    currentDateTime += milliSecs;
    this.repaint();
  }

  /** Draw the time string on the panel center. **/
  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Format the time string.
    String dateTimeString = dateFormat.format(new Date(currentDateTime));

    // Use our choice for the font.
    g.setFont(font);

    // Do the size and placement calculations only for the first paint  
    if (firstPass) {
       // Get measures needed to center the message
      FontMetrics fm = g.getFontMetrics();

      // How many pixels wide is the string
      int msg_width = fm.stringWidth(dateTimeString);

      // Use the string width to find the starting point
      fMsgX = getSize().width/2 - msg_width/2;

      // How far above the baseline can the font go?
      int ascent = fm.getMaxAscent();

      // How far below the baseline?
      int descent= fm.getMaxDescent();

      // Use the vertical height of this font to find
      // the vertical starting coordinate
      fMsgY = getSize().height/2 - descent/2 + ascent/2;
      
      firstPass = false;
    }    
    g.drawString(dateTimeString, fMsgX, fMsgY);    
  }
  
  public void reset() {
    init();
    this.repaint();
  }

}
